package com.aishua.fire.config.jwtsecurity.res;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import org.springframework.security.web.FilterInvocation;

import lombok.extern.slf4j.Slf4j;

import com.aishua.fire.common.constant.PermInitConstants;
import com.aishua.fire.common.constant.SessionConstants;
import com.aishua.fire.common.eenum.WhiteInterfaceEnum;
import com.aishua.fire.config.init.Init;
import com.aishua.fire.jpa.AccountteamDao;
import com.aishua.fire.jpa.entity.Accountteam;


@Slf4j
@Service
public class MyAccessDecisionManager implements AccessDecisionManager {

	@Autowired
	private AccountteamDao accountteamDao;
	
	/**
	 * 判断是否拥有权限的决策方法,获取角色匹配信息
	 */
	@Override
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
//		log.info("MyAccessDecisionManager.decide进来了");
	    //测试时请将此处直接注释掉,然后直接return
		/*if(configAttributes == null) {
            return;
		}*/
		
		//1.如果在白名单列表,放行
		HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
		if(Init.isNoValidateInterface(request) || WhiteInterfaceEnum.isInWriteList(request)) {
			String userName = (String) request.getAttribute(SessionConstants.JWT_USERNAME);
	        //通过用户名,获取对应用户的角色列表
	        List<Accountteam> accountteams = accountteamDao.findByAccountName(userName);
	        log.info("放行接口,用户名:{},当前登录用户拥有的角色列表信息:{}",userName,accountteams);
	        request.setAttribute(SessionConstants.ACCOUNTTEAM_LIST, accountteams);
			return;
		}
		
	
		
		String userName = (String) request.getAttribute(SessionConstants.JWT_USERNAME);
        //通过用户名,获取对应用户的角色列表
        List<Accountteam> accountteams = accountteamDao.findByAccountName(userName);
        log.info("用户名是:{},当前登录用户拥有的角色列表信息:{}",userName,accountteams);
        request.setAttribute(SessionConstants.ACCOUNTTEAM_LIST, accountteams);
        return;
        
        /*String uri = request.getRequestURI();
		String method = request.getMethod();
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();
        while(iterator.hasNext()) {
            ConfigAttribute configAttribute = iterator.next();
            //访问所请求资源所需要的权限
            String needRole = configAttribute.getAttribute();
            log.info("角色id为:{}拥有访问接口:{}+{}的权限 ",needRole,request.getMethod(),request.getRequestURI());
            
            //直接放行的接口
            if(PermInitConstants.NO_VALIDATE_PERM.equals(needRole)) {
            	return;
            }
            //只需要登录权限的直接放行
            if(PermInitConstants.Only_login.equals(needRole)) {
            	return;
            }
            
            if(PermInitConstants.ROLE_NO_USER3.equals(needRole)) {
            	Collection<ConfigAttribute> list = (Collection<ConfigAttribute>) request.getAttribute(SessionConstants.JWT_ROLES_TEMP);
            	log.info("list的值是:{}",list);
            	HashMap<PermInfo, Collection<ConfigAttribute>> resourceMap = Init.getUrlMap();
     	        for(Map.Entry<PermInfo, Collection<ConfigAttribute>> entry : resourceMap.entrySet()) {
     	        	PermInfo perm = entry.getKey();
     	        	if(perm.getRequestMethod().equalsIgnoreCase(method)) {
     	        		String regex = perm.getPermName();
    	        		if(Pattern.matches(regex, uri)) {
    	        			entry.setValue(list);
    	        			break;
    	        		}
     	        	}
     	        }
     	       throw new AccessDeniedException("2秒钟内重复的请求,请等待一会再试");
            }
            
            if(accountteams != null) {
	            for(Accountteam accountteam:accountteams) {
		        	String hasRole = String.valueOf(accountteam.getAccountteamId());
		        	log.info("当前账户拥有的角色Id:{} ",hasRole);
		        	 if(needRole.equals(hasRole)) {
		                 return;
		             }
		        }
            }
        }
		
        
        
	   //return;
        //TODO--没有权限
        throw new AccessDeniedException("对不起,你没有权限访问该资源,若有疑问请联系管理员");*/
//       throw new PermissionDeniedException("对不起,你没有权限访问该资源,若有疑问请联系管理员");
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}


}
